#encoding:UTF-8
from lib import mylib,config
import re
import MySQLdb
from time import mktime
from datetime import date


def parse_regex(content):
    try:
        result = []
        for i in re.finditer('(href=")(.*?)(")',content):
            link = i.group(2)
            link_save = 'http://ketquaxoso.24h.com.vn' + link
            print link_save
            result.append(link_save)
        return result
    except:
        return []
    


def parse_content(content):
    try:
        num1 = content.find('mở thưởng hôm nay')
        num2 = content.find('KẾT QUẢ XỔ SỐ 3 MIỀN',num1)
        data = content[num1:num2]
        return parse_regex(data)
    
    except:
        return []
    

def parse_url():
    url_main = config.URL_MAIN_XOSO
    content = mylib.get_data(url_main)
    list_link = parse_content(content)
    return list_link


def load_link_from_mysql(conn):
    try:
        try:
            conn.ping()
        except:
            conn = mylib.create_conn()
        cmd = "SELECT url ,id_tinh FROM xosourl"
        cursor = conn.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute(cmd)
        result = cursor.fetchall()
        cursor.close()
        
        return result
    except:
        return []


def insert_link_to_mysql(conn,url,id_tinh,date):
    try:
        conn.ping()
    except:
        conn = mylib.create_conn()
    cmd = "CALL insert_url_open('%s','%s','%s')" % (url,id_tinh,date)
    cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute(cmd)
    cursor.close()
    print "insert thanh cong"
 
    
def check_exit_link(conn,url):
    try:
        conn.ping()
    except:
        conn = mylib.create_conn()
    cmd = "SELECT * FROM url_mothuong"
    mydate = date.today()
    thisdate = mktime(mydate.timetuple())
    cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute(cmd)
    myresult = cursor.fetchall()
    if myresult == None:
        return False
    for link in myresult:
        exit_link = link['url']
        exit_date = link['time_open']
        if exit_link == url and thisdate == exit_date:
            return True
    return False
    

def process_link(conn):
    list_info = load_link_from_mysql(conn)
    list_link = parse_url()
    result = []
    mydate = date.today()
    savetime = mktime(mydate.timetuple())
    for info in list_info:
        buf = {}
        buf['url'] = info['url']
        buf['id_tinh'] = info['id_tinh']
        result.append(buf)
    for link in list_link:
        for buf_link in result:
            if link == buf_link['url']:
                if check_exit_link(conn, link) == False:
                    print "Insert 1 link"
                    insert_link_to_mysql(
                                      conn,buf_link['id_tinh'],
                                      buf_link['url'],int(savetime)
                                      )
                    break
    print "Xong tat ca"

 
if __name__ == '__main__':
    conn = mylib.create_conn()
    process_link(conn)
